import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Tooltip, message, Modal, Form, Input } from 'antd';
import {
  CopyOutlined,
  LikeOutlined,
  DislikeOutlined,
  DeleteOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import styles from '../styles/CustomControl.module.css';

import chatService from '@/api/services/chatService';

import { useContextSelector } from 'use-context-selector';
import { ChatContext } from '../context';
import useWindowWidth from '@/hooks/event/use-window-width';

import { removeRefTags } from '@/utils/regexRules';

import '../styles/reference.css';
import { removeThinkTags } from '@/utils/common';
import { useParams } from '@/router/hooks';
import { ChatItem } from '@/types/chat';
import { SvgIcon } from '@/components/icon';
interface CustomControlProps {
  isRobot: boolean;
  data: string;
  item?: ChatItem;
  chatId?: string;
  dataId?: string;
  defaultLike?: boolean;
  defaultDislike?: boolean;
  onDelete?: () => void;
  onRefresh?: () => void;
  workflowDebug?: boolean;
}

const CustomControl: React.FC<CustomControlProps> = ({
  isRobot,
  data,
  item,
  chatId,
  dataId,
  defaultLike,
  defaultDislike,
  onDelete,
  onRefresh,
  workflowDebug = false,
}) => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);

  const { appId, shareId } = useParams() as { appId: string; shareId: string };
  const { outLinkUid } = useContextSelector(ChatContext, (s) => s);
  const { isPc } = useWindowWidth();

  const isChatTest = useMemo(() => {
    const isInChatTestPage = location.pathname.includes('/workflow') || (location.pathname.includes('/orchestration') && chatId);
    return isInChatTestPage
  }, [location.pathname])

  useEffect(() => {
    // console.log(isRobot, data, chatId, dataId, defaultLike, defaultDislike);
    setLiked(defaultLike || false);
    setUnLiked(defaultDislike || false);
  }, [dataId]);

  const handleCopy = useCallback(() => {
    messageApi.success('复制成功');
  }, [messageApi]);

  const handleDelete = useCallback(() => {
    if (onDelete) {
      onDelete();
    }
  }, [onDelete]);

  const handleRefresh = useCallback(() => {
    setLiked(false);
    setUnLiked(false);
    if (onRefresh) {
      onRefresh();
    }
  }, [onRefresh]);

  const [liked, setLiked] = useState(false);
  const [unLiked, setUnLiked] = useState(false);

  const handleLikeClick = () => {
    console.log(data);
    console.log(chatId);
    console.log('item', item);
    chatId &&
      chatService.updateUserFeedback({
        appId: item?.appId || appId,
        chatId: chatId,
        dataId: dataId,
        chatItemId: dataId ?? '',
        shareId: item?.shareId || shareId,
        outLinkUid: shareId ? outLinkUid : '',
        ...(!liked ? { userGoodFeedback: 'yes' } : {}),
      });
    setLiked(!liked);
    if (unLiked) {
      setUnLiked(false);
    }
  };

  /* const handleDislikeClick = () => {
    setIsModalVisible(true);
    !unLiked && setIsModalVisible(true);
    unLiked && handleModalOk();
    form.resetFields();
  }; */
  const handleDislikeClick = () => {
    if (!unLiked) {
      setIsModalVisible(true);
      form.resetFields();
    } else {
      // setUnLiked(false);
      handleModalOk();
    }
  };

  const [selectedOptions, setSelectedOptions] = useState<string[]>([]);

  const handleOptionClick = (option: string) => {
    const currentOptions = form.getFieldValue('feedbackOptions') || [];
    const newOptions = currentOptions.includes(option)
      ? currentOptions.filter((item: string) => item !== option)
      : [...currentOptions, option];
    form.setFieldsValue({ feedbackOptions: newOptions });

    setSelectedOptions(newOptions);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      // 新增：将 feedbackOptions 和 feedbackMessage 拼接
      const feedbackOptions = values.feedbackOptions || [];
      const feedbackMessage = values.feedbackMessage || '';
      const allFeedback = [...feedbackOptions, feedbackMessage].filter(Boolean).join('|');
      chatId &&
        chatService.updateUserFeedback({
          appId: item?.appId || appId,
          chatId: chatId,
          dataId: dataId,
          chatItemId: dataId ?? '',
          shareId: item?.shareId || shareId,
          outLinkUid: shareId ? outLinkUid : '',
          ...(!unLiked
            ? { userBadFeedback: allFeedback ? allFeedback : '用户没有填写具体反馈内容' }
            : {}),
        });
      setUnLiked(!unLiked);
      setLiked(false);
      !unLiked && messageApi.success('反馈提交成功');
      form.resetFields();
      setSelectedOptions([]);
      setIsModalVisible(false);
    } catch (error) {
      !unLiked && messageApi.error('反馈提交失败');
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  useEffect(() => {
    setLiked(defaultLike === true);
  }, [defaultLike]);

  useEffect(() => {
    setUnLiked(defaultDislike === true);
  }, [defaultDislike]);

  return (
    <>
      <Modal
        className={`${!isPc && 'feedback-modal'}`}
        title={<div style={{ padding: 0, margin: 0 }}>不满意反馈</div>}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        footer={[
          /*   <Button key="back" onClick={handleModalCancel}>
              取消
            </Button>, */
          <div
            key="submit-button"
            style={{
              width: '100%',
              display: 'flex',
              justifyContent: 'center',
            }}
          >
            <Button
              type="primary"
              onClick={handleModalOk}
              style={{
                width: '100%',
                maxWidth: '300px', // 可根据需要调整最大宽度
                padding: '12px 0', // 增加垂直内边距，使按钮高度适中
              }}
            >
              提交反馈
            </Button>
          </div>,
        ]}
        style={
          !isPc
            ? {
              top: 'unset',
              bottom: 0,
              margin: 0,
              position: 'fixed',
              width: '100%',
              maxWidth: '100%',
              paddingBottom: 0,
              maxHeight: '48vh',
              left: 0,
            }
            : {}
        }
      >
        <Form form={form} layout="vertical" name="form_in_modal">
          <Form.Item name="feedbackOptions">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
              {['没有回答我的问题', '答案太长不想看', '试过了没有用', '看不懂'].map((option) => (
                <Button
                  key={option}
                  type={selectedOptions.includes(option) ? 'primary' : 'default'}
                  onClick={() => handleOptionClick(option)}
                  style={{ borderRadius: '16px' }}
                >
                  {option}
                </Button>
              ))}
            </div>
          </Form.Item>
          <Form.Item
            name="feedbackMessage"
            rules={[
              {
                required: false,
              },
            ]}
          >
            <Input.TextArea
              rows={4}
              style={{ resize: 'none' }}
              placeholder="您可以在此输入详细的反馈（可选）"
            />
          </Form.Item>
        </Form>
      </Modal>

      <div className="custom-control flex gap-1">
        {contextHolder}
        <Tooltip title="复制">
          <CopyToClipboard text={removeThinkTags(removeRefTags(data))?.trim()} onCopy={handleCopy}>
            <Button
              icon={
                // <CopyOutlined />
                <SvgIcon icon="ai-chat-copy" size="16" />
              }
              style={{ border: 'none', background: 'none' }}
              size="small"
            />
          </CopyToClipboard>
        </Tooltip>
        {isRobot ? (
          <>
            {onRefresh && (
              <Tooltip title="重新生成">
                <Button
                  icon={
                    // <SyncOutlined />
                    <SvgIcon icon="ai-chat-refresh" size="16" />
                  }
                  onClick={handleRefresh}
                  style={{ border: 'none', background: 'none' }}
                  size="small"
                />
              </Tooltip>
            )}
            {!workflowDebug && !isChatTest && (
              <>
                {chatId ? (
                  <Tooltip title="点赞">
                    <Button
                      icon={
                        // <LikeOutlined />
                        liked ?
                          <SvgIcon icon="ai-chat-zan" size="16" />
                          :
                          <SvgIcon icon="ai-chat-zan-line" size="16" />
                      }
                      style={{
                        border: 'none',
                        color: liked ? 'var(--brand-color)' : '#000',
                        background: 'none',
                        // display: unLiked ? 'none' : 'unset',
                        display: 'unset',
                      }}
                      size="small"
                      onClick={handleLikeClick}
                      className="hover:!text-[var(--brand-color)]"
                    />
                  </Tooltip>
                ) : (
                  liked && <Button
                    disabled={true}
                    icon={
                      // <LikeOutlined />
                      <SvgIcon icon="ai-chat-zan" size="16" />
                    }
                    style={{
                      border: 'none',
                      color: liked ? 'var(--brand-color)' : '#000',
                      background: 'none',
                      // display: unLiked ? 'none' : 'unset',
                      display: 'unset',
                    }}
                    size="small"
                  />
                )}

                {chatId ? (
                  <Tooltip title="反馈">
                    <Button
                      icon={
                        // <DislikeOutlined />
                        unLiked ? <SvgIcon icon="ai-chat-cai" size="16" /> : <SvgIcon icon="ai-chat-cai-line" size="16" />
                      }
                      style={{
                        border: 'none',
                        color: unLiked ? 'var(--brand-color)' : '#000',
                        background: 'none',
                        // display: liked ? 'none' : 'inline-block',
                        display: 'unset',
                      }}
                      size="small"
                      onClick={handleDislikeClick}
                      className="hover:!text-[var(--brand-color)]"
                    />
                  </Tooltip>
                ) : (
                  unLiked && <Button
                    disabled={true}
                    icon={
                      // <DislikeOutlined />
                      <SvgIcon icon="ai-chat-cai" size="16" />
                    }
                    style={{
                      border: 'none',
                      color: unLiked ? 'var(--brand-color)' : '#000',
                      background: 'none',
                      // display: liked ? 'none' : 'inline-block',
                      display: 'unset',
                    }}
                    size="small"
                  />
                )}
              </>
            )}
          </>
        ) : (
          <>
            {onRefresh && (
              <Tooltip title="重新生成">
                <Button
                  icon={
                    // <SyncOutlined />
                    <SvgIcon icon="ai-chat-refresh" size="16" />
                  }
                  onClick={handleRefresh}
                  style={{ border: 'none', background: 'none' }}
                  size="small"
                />
              </Tooltip>
            )}
            {/* <div className={styles['divider']}></div> */}
            {onDelete && (
              <Tooltip title="删除">
                <Button
                  icon={
                    // <DeleteOutlined />
                    <SvgIcon icon="ai-chat-delete" size="16" />
                  }
                  onClick={handleDelete}
                  style={{ border: 'none', background: 'none' }}
                  size="small"
                />
              </Tooltip>
            )}
          </>
        )}
      </div>
    </>
  );
};

export default CustomControl;
